

import React, { useState } from 'react';
import { View, Text, ScrollView, TouchableOpacity, Modal, Alert, } from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useRouter } from 'expo-router';
import { FontAwesome6 } from '@expo/vector-icons';
import { LinearGradient } from 'expo-linear-gradient';
import styles from './styles';

interface StatisticsData {
  total: number;
  completed: number;
  pending: number;
  avgTime: string;
  trend: string;
  completedTrend: string;
  pendingTrend: string;
  timeTrend: string;
}

type StatisticsType = 'personal' | 'department';
type ExportFormat = 'excel' | 'pdf' | '';

const DataStatisticsScreen = () => {
  const router = useRouter();
  const [selectedStatisticsType, setSelectedStatisticsType] = useState<StatisticsType>('personal');
  const [isExportModalVisible, setIsExportModalVisible] = useState(false);
  const [selectedExportFormat, setSelectedExportFormat] = useState<ExportFormat>('');
  const [isExportSuccessVisible, setIsExportSuccessVisible] = useState(false);

  const statisticsData: Record<StatisticsType, StatisticsData> = {
    personal: {
      total: 156,
      completed: 142,
      pending: 12,
      avgTime: '2.3h',
      trend: '+12%',
      completedTrend: '+8%',
      pendingTrend: '持平',
      timeTrend: '-15%'
    },
    department: {
      total: 489,
      completed: 456,
      pending: 33,
      avgTime: '3.1h',
      trend: '+18%',
      completedTrend: '+15%',
      pendingTrend: '+5%',
      timeTrend: '-8%'
    }
  };

  const currentData = statisticsData[selectedStatisticsType];

  const weekData = [
    { day: '周一', value: 8, height: 60 },
    { day: '周二', value: 12, height: 80 },
    { day: '周三', value: 6, height: 45 },
    { day: '周四', value: 14, height: 90 },
    { day: '周五', value: 10, height: 70 },
    { day: '周六', value: 3, height: 25 },
    { day: '周日', value: 2, height: 15 }
  ];

  const typeDistributionData = [
    { name: '请假申请', percentage: 45, count: 70, color: '#969FFF' },
    { name: '采购申请', percentage: 28, count: 44, color: '#10B981' },
    { name: '报销申请', percentage: 18, count: 28, color: '#3B82F6' },
    { name: '其他', percentage: 9, count: 14, color: '#8B5CF6' }
  ];

  const handleBackPress = () => {
    if (router.canGoBack()) {
      router.back();
    }
  };

  const handleExportPress = () => {
    setIsExportModalVisible(true);
  };

  const handleCloseExportModal = () => {
    setIsExportModalVisible(false);
    setSelectedExportFormat('');
  };

  const handleExportFormatSelect = (format: ExportFormat) => {
    setSelectedExportFormat(format);
  };

  const handleConfirmExport = () => {
    if (!selectedExportFormat) {
      Alert.alert('提示', '请选择导出格式');
      return;
    }
    
    setIsExportModalVisible(false);
    setSelectedExportFormat('');
    
    setTimeout(() => {
      setIsExportSuccessVisible(true);
    }, 500);
  };

  const handleCloseSuccess = () => {
    setIsExportSuccessVisible(false);
  };

  const handleStatisticsTypeChange = (type: StatisticsType) => {
    setSelectedStatisticsType(type);
  };

  const getOverviewTitle = () => {
    return selectedStatisticsType === 'department' ? '部门数据概览' : '个人数据概览';
  };

  const getEfficiencyTitle = () => {
    return selectedStatisticsType === 'department' ? '部门审批效率分析' : '个人审批效率分析';
  };

  const getDistributionTitle = () => {
    return selectedStatisticsType === 'department' ? '部门审批类型分布' : '个人审批类型分布';
  };

  const getTrendTitle = () => {
    return selectedStatisticsType === 'department' ? '部门审批趋势' : '个人审批趋势';
  };

  const getDetailedTitle = () => {
    return selectedStatisticsType === 'department' ? '部门详细数据' : '个人详细数据';
  };

  const renderStatisticsCard = (
    value: string | number,
    label: string,
    trend: string,
    isGradient: boolean = false,
    valueColor?: string
  ) => (
    <View style={styles.statsCard}>
      <Text style={[styles.statsValue, isGradient && styles.gradientText, valueColor && { color: valueColor }]}>
        {value}
      </Text>
      <Text style={styles.statsLabel}>{label}</Text>
      <View style={styles.statsTrend}>
        <FontAwesome6 
          name={trend.startsWith('+') ? 'arrow-up' : trend.startsWith('-') ? 'arrow-down' : 'minus'} 
          size={10} 
          color={trend.startsWith('+') || trend === '持平' ? '#10B981' : '#F59E0B'} 
        />
        <Text style={[styles.statsTrendText, trend.startsWith('+') || trend === '持平' ? styles.positiveTrend : styles.neutralTrend]}>
          {trend}
        </Text>
      </View>
    </View>
  );

  const renderChartBar = (item: typeof weekData[0], index: number) => (
    <View key={index} style={styles.chartBarContainer}>
      <LinearGradient
        colors={['#969FFF', '#5147FF']}
        start={{ x: 0, y: 0 }}
        end={{ x: 1, y: 1 }}
        style={[styles.chartBar, { height: `${item.height}%` }]}
      />
      <Text style={styles.chartDayLabel}>{item.day}</Text>
      <Text style={styles.chartValueLabel}>{item.value}</Text>
    </View>
  );

  const renderDistributionItem = (item: typeof typeDistributionData[0], index: number) => (
    <View key={index} style={styles.distributionItem}>
      <View style={styles.distributionInfo}>
        <View style={[styles.distributionColor, { backgroundColor: item.color }]} />
        <Text style={styles.distributionName}>{item.name}</Text>
        <Text style={styles.distributionPercentage}>{item.percentage}%</Text>
      </View>
      <Text style={styles.distributionCount}>{item.count}</Text>
    </View>
  );

  const renderDetailItem = (
    icon: string,
    iconColor: string,
    title: string,
    subtitle: string,
    value: string,
    valueColor: string
  ) => (
    <View style={styles.detailItem}>
      <View style={styles.detailInfo}>
        <LinearGradient
          colors={iconColor === 'green' ? ['#10B981', '#059669'] : iconColor === 'blue' ? ['#3B82F6', '#2563EB'] : ['#969FFF', '#5147FF']}
          start={{ x: 0, y: 0 }}
          end={{ x: 1, y: 1 }}
          style={styles.detailIcon}
        >
          <FontAwesome6 name={icon} size={14} color="#FFFFFF" />
        </LinearGradient>
        <View style={styles.detailText}>
          <Text style={styles.detailTitle}>{title}</Text>
          <Text style={styles.detailSubtitle}>{subtitle}</Text>
        </View>
      </View>
      <Text style={[styles.detailValue, { color: valueColor }]}>{value}</Text>
    </View>
  );

  return (
    <SafeAreaView style={styles.container}>
      {/* 顶部导航栏 */}
      <View style={styles.header}>
        <View style={styles.headerLeft}>
          <TouchableOpacity style={styles.backButton} onPress={handleBackPress}>
            <FontAwesome6 name="arrow-left" size={18} color="#6B7280" />
          </TouchableOpacity>
          <Text style={styles.headerTitle}>数据统计</Text>
        </View>
        <TouchableOpacity style={styles.exportButton} onPress={handleExportPress}>
          <LinearGradient
            colors={['#969FFF', '#5147FF']}
            start={{ x: 0, y: 0 }}
            end={{ x: 1, y: 1 }}
            style={styles.exportButtonGradient}
          >
            <FontAwesome6 name="download" size={12} color="#FFFFFF" />
            <Text style={styles.exportButtonText}>导出</Text>
          </LinearGradient>
        </TouchableOpacity>
      </View>

      <ScrollView style={styles.content} showsVerticalScrollIndicator={false}>
        {/* 统计维度切换 */}
        <View style={styles.dimensionTabs}>
          <View style={styles.tabContainer}>
            <TouchableOpacity
              style={[
                styles.tab,
                selectedStatisticsType === 'personal' ? styles.tabActive : styles.tabInactive
              ]}
              onPress={() => handleStatisticsTypeChange('personal')}
            >
              {selectedStatisticsType === 'personal' ? (
                <LinearGradient
                  colors={['#969FFF', '#5147FF']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.tabGradient}
                >
                  <Text style={styles.tabActiveText}>个人统计</Text>
                </LinearGradient>
              ) : (
                <Text style={styles.tabInactiveText}>个人统计</Text>
              )}
            </TouchableOpacity>
            <TouchableOpacity
              style={[
                styles.tab,
                selectedStatisticsType === 'department' ? styles.tabActive : styles.tabInactive
              ]}
              onPress={() => handleStatisticsTypeChange('department')}
            >
              {selectedStatisticsType === 'department' ? (
                <LinearGradient
                  colors={['#969FFF', '#5147FF']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.tabGradient}
                >
                  <Text style={styles.tabActiveText}>部门统计</Text>
                </LinearGradient>
              ) : (
                <Text style={styles.tabInactiveText}>部门统计</Text>
              )}
            </TouchableOpacity>
          </View>
        </View>

        {/* 数据概览卡片 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{getOverviewTitle()}</Text>
          <View style={styles.statsGrid}>
            {renderStatisticsCard(currentData.total, '总审批数', currentData.trend, true)}
            {renderStatisticsCard(currentData.completed, '已完成', currentData.completedTrend, false, '#10B981')}
            {renderStatisticsCard(currentData.pending, '待处理', currentData.pendingTrend, false, '#F59E0B')}
            {renderStatisticsCard(currentData.avgTime, '平均时长', currentData.timeTrend, false, '#3B82F6')}
          </View>
        </View>

        {/* 审批效率分析 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{getEfficiencyTitle()}</Text>
          <View style={styles.efficiencyCard}>
            <View style={styles.chartContainer}>
              {weekData.map((item, index) => renderChartBar(item, index))}
            </View>
            <View style={styles.chartFooter}>
              <Text style={styles.chartFooterLabel}>本周处理量趋势</Text>
              <Text style={styles.chartFooterValue}>平均: 8.1个/天</Text>
            </View>
          </View>
        </View>

        {/* 审批类型分布 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{getDistributionTitle()}</Text>
          <View style={styles.distributionCard}>
            {typeDistributionData.map((item, index) => renderDistributionItem(item, index))}
          </View>
        </View>

        {/* 审批趋势图表 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{getTrendTitle()}</Text>
          <View style={styles.trendCard}>
            <View style={styles.trendItem}>
              <Text style={styles.trendLabel}>本月处理量</Text>
              <Text style={styles.trendValueGradient}>48</Text>
            </View>
            <View style={styles.trendItem}>
              <Text style={styles.trendLabel}>上月处理量</Text>
              <Text style={styles.trendValueSecondary}>42</Text>
            </View>
            <View style={styles.trendItem}>
              <Text style={styles.trendLabel}>环比增长</Text>
              <Text style={styles.trendValuePositive}>+14.3%</Text>
            </View>
          </View>
        </View>

        {/* 详细数据列表 */}
        <View style={styles.section}>
          <Text style={styles.sectionTitle}>{getDetailedTitle()}</Text>
          <View style={styles.detailList}>
            {renderDetailItem('clock', 'primary', '最长审批时长', '项目预算申请', '48h', '#F59E0B')}
            {renderDetailItem('bolt', 'green', '最短审批时长', '日常采购申请', '15min', '#10B981')}
            {renderDetailItem('check-circle', 'blue', '通过率', '本月数据', '92.3%', '#10B981')}
          </View>
        </View>
      </ScrollView>

      {/* 导出报告模态框 */}
      <Modal
        visible={isExportModalVisible}
        transparent={true}
        animationType="fade"
        onRequestClose={handleCloseExportModal}
      >
        <View style={styles.modalOverlay}>
          <View style={styles.modalContent}>
            <Text style={styles.modalTitle}>选择导出格式</Text>
            <View style={styles.exportOptions}>
              <TouchableOpacity
                style={[
                  styles.exportOption,
                  selectedExportFormat === 'excel' && styles.exportOptionSelected
                ]}
                onPress={() => handleExportFormatSelect('excel')}
              >
                <LinearGradient
                  colors={['#10B981', '#059669']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.exportOptionIcon}
                >
                  <FontAwesome6 name="file-excel" size={16} color="#FFFFFF" />
                </LinearGradient>
                <View style={styles.exportOptionText}>
                  <Text style={styles.exportOptionTitle}>Excel格式</Text>
                  <Text style={styles.exportOptionSubtitle}>详细数据表格</Text>
                </View>
                <FontAwesome6 name="chevron-right" size={14} color="#6B7280" />
              </TouchableOpacity>

              <TouchableOpacity
                style={[
                  styles.exportOption,
                  selectedExportFormat === 'pdf' && styles.exportOptionSelected
                ]}
                onPress={() => handleExportFormatSelect('pdf')}
              >
                <LinearGradient
                  colors={['#EF4444', '#DC2626']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.exportOptionIcon}
                >
                  <FontAwesome6 name="file-pdf" size={16} color="#FFFFFF" />
                </LinearGradient>
                <View style={styles.exportOptionText}>
                  <Text style={styles.exportOptionTitle}>PDF格式</Text>
                  <Text style={styles.exportOptionSubtitle}>图表报告</Text>
                </View>
                <FontAwesome6 name="chevron-right" size={14} color="#6B7280" />
              </TouchableOpacity>
            </View>

            <View style={styles.modalButtons}>
              <TouchableOpacity style={styles.cancelButton} onPress={handleCloseExportModal}>
                <Text style={styles.cancelButtonText}>取消</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.confirmButton} onPress={handleConfirmExport}>
                <LinearGradient
                  colors={['#969FFF', '#5147FF']}
                  start={{ x: 0, y: 0 }}
                  end={{ x: 1, y: 1 }}
                  style={styles.confirmButtonGradient}
                >
                  <Text style={styles.confirmButtonText}>确认导出</Text>
                </LinearGradient>
              </TouchableOpacity>
            </View>
          </View>
        </View>
      </Modal>

      {/* 导出成功提示 */}
      <Modal
        visible={isExportSuccessVisible}
        transparent={true}
        animationType="fade"
        onRequestClose={handleCloseSuccess}
      >
        <View style={styles.successOverlay}>
          <View style={styles.successContent}>
            <LinearGradient
              colors={['#10B981', '#059669']}
              start={{ x: 0, y: 0 }}
              end={{ x: 1, y: 1 }}
              style={styles.successIcon}
            >
              <FontAwesome6 name="check" size={24} color="#FFFFFF" />
            </LinearGradient>
            <Text style={styles.successTitle}>导出成功</Text>
            <Text style={styles.successMessage}>报告已生成，请查收</Text>
            <TouchableOpacity style={styles.successButton} onPress={handleCloseSuccess}>
              <LinearGradient
                colors={['#969FFF', '#5147FF']}
                start={{ x: 0, y: 0 }}
                end={{ x: 1, y: 1 }}
                style={styles.successButtonGradient}
              >
                <Text style={styles.successButtonText}>确定</Text>
              </LinearGradient>
            </TouchableOpacity>
          </View>
        </View>
      </Modal>
    </SafeAreaView>
  );
};

export default DataStatisticsScreen;

